package cmd

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"hobby-mate/config/db"
	"hobby-mate/middleware/gateway"
	"hobby-mate/middleware/globalLogger"
	"hobby-mate/middleware/limit"
	"hobby-mate/routers"
	"os"
	"os/exec"
)

// ---------------------------------------常量组-----开始
const ip = "127.0.0.1"
const colon = ":"
const port = "9999"
const fullUrl = ip + colon + port
const pink = "\033[35m"
const errorRed = "\033[31m"
const reset = "\033[0m"

//---------------------------------------常量组-----结束

// ---------------------------------------线程通道-----开始
var buildDbServiceChannel = make(chan bool)
var initSwagChannel = make(chan bool)

//---------------------------------------线程通道-----结束

// startInitSwag 启动初始化swagger服务
// 执行swag init -g cmd/applicationMain.go
// @title 寻伴
// @version v1 API
// @description 找啊找呀找朋友找到几个好朋友～🧑‍🤝‍🧑
// @host  127.0.0.1:9999
// @BasePath /api/
func startInitSwag() {
	cmd := exec.Command("swag", "init", "-g", "cmd/applicationMain.go")
	err := cmd.Run()
	if err != nil {
		fmt.Printf("%s未能建立swagger%s\n", errorRed, reset)
		globalLogger.Write("未能建立swagger，程序持续执行中"+err.Error(), "error")
	} else {
		initSwagChannel <- true
	}

}

// startRouterService 启动路由服务
func startRouterService() {
	routerServer := gin.Default()
	routerServer.
		Use(gin.LoggerWithConfig(globalLogger.RecordToFile())).
		Use(globalLogger.Recover).
		Use(limit.ApiLimit).
		Use(gateway.ApiCenter)
	//拦截_login接口的返回值，把ReturnOkSuccess中的data返回值set到cookie中，并改成nil返回给前端
	//构造路由
	(&routers.
		BaseRouter{Engine: routerServer}).
		WithAdminRouter().
		WithWechatRouter().
		WithCommonSwaggerRouter()
	//启动服务
	err := routerServer.Run(fullUrl)
	if err != nil {
		fmt.Printf("%s未能建立路由%s\n", pink, reset)
		globalLogger.Write("路由服务启动失败", "error")
		return
	}
}

// startCheckAndCreateDb 启动检查数据库并创建
func startCheckAndCreateDb() {
	if err := db.CheckAndCreateDb(); err != nil {
		fmt.Printf("%s未能建立数据库，服务退出%s\n", pink, reset)
		globalLogger.Write("s未能建立数据库，服务退出", "error")
		os.Exit(1)
	}
	buildDbServiceChannel <- true
}

// waitForBuildDb 等待建立数据库
func waitForBuildDb() {
	<-buildDbServiceChannel
	fmt.Printf("%s数据库已建立,无需再次创建%s\n", pink, reset)
}

// waitForSwag 等待swagger文档生成
func waitForSwag() {
	<-initSwagChannel
	fmt.Printf("%sswag文档已更新%s\n", pink, reset)
}

// TaskQueue 服务启动执行的任务队列
func taskQueue() {
	go waitForBuildDb()
	go waitForSwag()
	go startCheckAndCreateDb()
	go startInitSwag()
	startRouterService()
}

// Exec app启动
func Exec() {
	taskQueue()
}
